//
//  KAInfoVC.swift
//  kano
//
//  Created by Sophia on 2024/8/22.
//

import UIKit
import SwiftyJSON
import KakaJSON
import AVFoundation

class KAInfoVC: KABaseVC {
    
    lazy var var_dataArray = [KASectionInfo]()
    
    var var_selectGender: String = ""
    var var_selectBirthday: String = ""
    
    var applyModel: KAApply
    var var_pageModel: KAApplyPageElement?
    var var_model: KABasic = KABasic()
    
    static let var_itemCellId = "KAApplyInfoCell"
    lazy var var_tableView: UITableView = {
        let var_tableView = UITableView(frame: CGRect(x: 0.0, y: UIDevice.ka_fullNavHeight, width: view.width, height: UIDevice.ka_viewHeight), style: .grouped)
        var_tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        var_tableView.backgroundColor = .colorFFF
        var_tableView.register(KAApplyInfoCell.self, forCellReuseIdentifier: Self.var_itemCellId)
        var_tableView.dataSource = self
        var_tableView.delegate = self
        var_tableView.separatorStyle = .none
        var_tableView.register(KAApplyTitleHeader.self, forHeaderFooterViewReuseIdentifier: "KAApplyTitleHeader")
        var_tableView.register(KAApplySectionFooter.self, forHeaderFooterViewReuseIdentifier: "KAApplySectionFooter")
        var_tableView.tableFooterView = var_tableFooter
        //var_tableView.separatorColor = UIColor(0xffffff, alphaVaule: 0.15)
        return var_tableView
    }()
    
    lazy var var_tableFooter: KAApplyFooter = {
        let var_tableFooter = KAApplyFooter()
        var_tableFooter.var_loginButton.addTarget(self, action: #selector(ka_nextBtnClick), for: .touchUpInside)
        return var_tableFooter
    }()
    
    var livenessId: String = ""
    
    init(model: KAApply) {
        applyModel = model
        var_pageModel = model.isExtendedSubCreditEligible?.brokerageFee?.first
        
        let dicResult = dealStringToObject(with: model.isExtendedSubCreditEligible?.inviteRewardResponse) as? [String : Any]
        let submitDic = dicResult?["identityDocumentNumber"] as? String
        if submitDic != nil {
            let submit = submitDic!.kj.model(KABasic.self)
            var_model = submit!
            //活体livenessId不能直接放到KABasic模型中，会影响最后一步提交数据；在这里直接从JSON对象中获取；
            if let jsonData = submitDic!.data(using: .utf8) {
                let json = try? JSON(data: jsonData)
                if let livenessed = json?["authlivenessindicator"].string {
                    self.livenessId = livenessed
                    print("======")
                }
            }
        }
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func customNavBackAction() {
//        navigationController?.popToRootViewController(animated: true)
        ka_requestExitReason()
    }
}

extension KAInfoVC {
    
    func ka_requestExitReason() {
        let paramDic: [String : Any] = [
            "softwareUpdateVersions": KAUserManager.shared.user.softwareUpdateVersions, "sliderVerificationStatus": 0
        ]
        view.showLoading()
        loginProvider.request(.getExitReason(paramDic)) { [self] result in
            view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<[KAExitReasonModel]>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.voucherQuantity else {
                                view.makeToast("Verification failure"); return
                            }
                            let exitReasonView = KAExitReasonPusher { (content, isSuccess) in
                                if (isSuccess) {
                                    self.navigationController?.popViewController(animated: true)
                                }
                            }
                            exitReasonView.dataArray = content
                            exitReasonView.ka_show()
                        } else {
                            self.view.makeToast(badNetWorking)
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    @objc func ka_nextBtnClick() {
        
        guard var_model.bankVerificationNumberInput.verifyBvn == true else {
            view.makeToast("Please enter the correct ID number"); return
        }
        if var_model.firstNameUser.isEmpty {
            view.makeToast("First Name Cannot Be Empty"); return
        }
        if var_model.lastNameUser.isEmpty {
            view.makeToast("Last Name Cannot Be Empty"); return
        }
        guard var_model.firstNameUser.verifyName  == true else {
            view.makeToast("First Name Cannot contain spaces or special characters"); return
        }
        if !var_model.middleNameUser.isEmpty && var_model.middleNameUser.verifyName  == false {
            view.makeToast("Middle Name Cannot contain spaces or special characters"); return
        }
        guard var_model.lastNameUser.verifyName  == true else {
            view.makeToast("Last Name Cannot contain spaces or special characters"); return
        }
        
        
        //btn report
        let btnInfo = KABtnInfo(eleId: "legal_agreement_repository", pageId: "individualIdentificationDetails", clickTime: Date.ka_currentData())
        KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
        
        let data = [ "identityInformation": var_model.kj.JSONObject()]
        let paramDic: [String : Any] = [
            "currentBusinessArgument" : applyModel.isExtendedSubCreditEligible?.brokerageFee?.first?.currentBusinessArgument ?? "",
//            "dailyOverdueRate" : "20002", //1.0.6去掉了该参数
            "softwareUpdateVersions" : KAUserManager.shared.user.softwareUpdateVersions,
            "data" : data
        ]
        view.showLoading()
        applyProvider.request(.submit(paramDic)) { [self] result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAContent>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            ka_requestResult()
                        } else {
                            view.hideLoading()
                            self.view.makeToast(badNetWorking)
                        }
                    }
                }else {
                    view.hideLoading()
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                view.hideLoading()
                print(error.localizedDescription)
            }
        }
        
        
        var basicDic = var_model.kj.JSONObject()
        //防止换设备登录需将已缓存的livenessId继续缓存
        basicDic["authlivenessindicator"] = self.livenessId  //"1db87d28-b8cd-4996-8f58-e02b2ec7a6a4"
        let cacheDic: [String : Any] = [
            "softwareUpdateVersions" : KAUserManager.shared.user.softwareUpdateVersions,
            "loanStatementList" : "identityDocumentNumber",
            "monetaryValue" : basicDic.jsonString() ?? ""
        ]
        applyProvider.request(.cache(cacheDic)) { [self] result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAContent>.handleResponseData(response.data) { isSuccess, message, response in
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    func ka_requestResult() {
        let paramDic: [String : Any] = [
            "currentBusinessArgument": var_pageModel!.currentBusinessArgument, "requestCode": "2"
        ]
        applyProvider.request(.submitStatus(paramDic)) { [self] result in
            view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    guard let responseString = String(data: response.data, encoding: .utf8) else {
                        return
                    }
                    let jsonData = JSON(parseJSON: responseString)
                    guard let dictionary = jsonData.dictionaryObject else {
                        return
                    }
                    guard let data = dictionary["data"] as? [String : Any] else {
                        ka_requestResult()
                        return
                    }
                    guard let code = data["dailyOverdueRate"] as? String else {
                        return
                    }
                    
                    if code == "2" {
                        //灰度用户且没有做过活体，去活体识别
                        if applyModel.isExtendedSubCreditEligible?.liveCreditUser == true && livenessId.isEmpty {
                            toliveness()
                        } else {
                            let vc = KAContactVC(model: applyModel)
                            vc.var_basicModel = var_model
                            self.navigationController?.pushViewController(vc, animated: true)
                        }
                    }
                    else if code == "1" {
                        guard let content = data["data"] as? [String : Any] else {
                            return
                        }
                        guard let array = content["otherUserGidList"] as? Array<String> else {
                            return
                        }
                        showBVNAlert(Oldgid: array.first!)
                    }
                    else {
                        self.view.makeToast(data["verificationDigit"] as? String)
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    func toliveness() {
        let status = AVCaptureDevice.authorizationStatus(for: .video)
        switch status {
        case .notDetermined:
            // 用户尚未选择，弹出权限请求
            let data = KAPageInfo(eleId: "original_camera_verification", path: "\(KAInfoVC.self)")
            KAReport.ka_reportWith(type: .page, data: data.kj.JSONObject())
            AVCaptureDevice.requestAccess(for: .video) { [self] granted in
                if granted {
                    //用户同意了摄像头权限
                    let btnInfo = KABtnInfo(eleId: "alternate_camera_active", pageId: "individualIdentificationDetails", clickTime: Date.ka_currentData())
                    KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
                    DispatchQueue.main.sync {
                        KAAdvance.shared.setData(model: applyModel, basic: var_model)
                        KAAdvance.shared.getAccessToken()
                    }
                } else {
                    let btnInfo = KABtnInfo(eleId: "alternate_camera_inactive", pageId: "individualIdentificationDetails", clickTime: Date.ka_currentData())
                    KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
                    DispatchQueue.main.sync {
                        showAlert()
                    }
                }
            }
        case .restricted, .denied:
            // 用户拒绝了权限或权限受到限制
            showAlert()
        case .authorized:
            // 用户已授权使用摄像头
            let maxRetryCount = Int(self.applyModel.isExtendedSubCreditEligible?.livecreditresult ?? "0")
            if KAAdvance.shared.retryCount < maxRetryCount ?? 0 {
                KAAdvance.shared.setData(model: applyModel, basic: var_model)
                KAAdvance.shared.getAccessToken()
            } else {
                //如果次数达到后台配置上限仍未识别成功，放弃活体识别直接去备用联系人
                let vc = KAContactVC(model: self.applyModel)
                vc.var_basicModel = var_model
                UIViewController.ka_current().navigationController?.pushViewController(vc, animated: true)
            }
        @unknown default:
            break
        }
    }
    
    func showAlert() {
        let data = KAPageInfo(eleId: "original_camera_configuration", path: "\(KAInfoVC.self)")
        KAReport.ka_reportWith(type: .page, data: data.kj.JSONObject())
        let message = "We need your camera access in order to complete facial recognition."
        let alert = KAAlertView.alert(withTitle: "Prompt", subtitle: message) {_ in }
        alert.addAction(KAAlertAction(title: "Cancel", titleColor: .black, backgroundColor: .clear) { [self] action in
            let btnInfo = KABtnInfo(eleId: "alternate_config_inactive", pageId: "individualIdentificationDetails", clickTime: Date.ka_currentData())
            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
            let vc = KAContactVC(model: applyModel)
            vc.var_basicModel = var_model
            self.navigationController?.pushViewController(vc, animated: true)
        })
        alert.addAction(KAAlertAction(title: "Authorized guide", titleColor: .blue, backgroundColor: .clear) { action in
            let btnInfo = KABtnInfo(eleId: "alternate_config_active", pageId: "individualIdentificationDetails", clickTime: Date.ka_currentData())
            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
            UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
        })
        alert.show()
    }
    
    func showBVNAlert(Oldgid: String) {
        let subStr = "BVN:\(var_model.bankVerificationNumberInput)"
        let alert = KAAlertView.alert(withTitle: "Please confirm the ID number is correct.", subtitle: subStr) { clickedTitle in
        }
        alert.addAction(KAAlertAction(title: "Correct", titleColor: .black, backgroundColor: .clear) { action in
            self.checkBvn(oldId: Oldgid)
        })
        alert.addAction(KAAlertAction(title: "Re-enter", titleColor: .blue, backgroundColor: .clear))
        alert.show()
    }
    
    func checkBvn(oldId: String) {
        
        let paramDic: [String : Any] = [
            "temporaryToken" : var_model.bankVerificationNumberInput,
            "validityExpirationDate" : oldId,
            "softwareUpdateVersions" : KAUserManager.shared.user.softwareUpdateVersions,
        ]
        view.showLoading()
        applyProvider.request(.checkOldMobile(paramDic)) { [self] result in
            switch result {
            case .success(let response):
                view.hideLoading()
                if response.statusCode == 200 {
                    NetResponse<KAOldMobileInfo>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.voucherQuantity else { return }
                            self.correctAlert(info: content)
                        } else {
                            view.hideLoading()
                            self.view.makeToast(badNetWorking)
                        }
                    }
                }else {
                    view.hideLoading()
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                view.hideLoading()
                print(error.localizedDescription)
            }
        }
    }
    
    func correctAlert(info: KAOldMobileInfo) {
        let titleStr = "Your BVN number has been used by phone number \(info.notificationMessage)"
        let subStr = "Please log in with your original phone number or contact customer service for consultation."
        let alertView = KAApplyIdAlert(title: titleStr, subTitle: subStr)
        alertView.ka_show()
    }
}

extension KAInfoVC {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let data = KAPageInfo(eleId: "individualIdentificationDetails", path: "\(KAInfoVC.self)")
        KAReport.ka_reportWith(type: .page, data: data.kj.JSONObject())
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        ka_configData()
        ka_setUI()
    }
    func ka_configData() {
        let idRow = KARowInfo(placeHolder: "BVN" )
        let idSectionInfo = KASectionInfo(showHeader: true, sectionTitle: "BVN", sectionList: [idRow], type: .identification)
        
        let firstName = KARowInfo(placeHolder: "Please enter first name")
        let firstNameInfo = KASectionInfo(showHeader: true, sectionTitle: "First name", sectionList: [firstName], type: .firstName)
        
        let middleName = KARowInfo(placeHolder: "Please enter middle name")
        let middleNameInfo = KASectionInfo(showHeader: true, sectionTitle: "Middle name", sectionList: [middleName], type: .middleName)
        
        let lastName = KARowInfo(placeHolder: "Please enter last name")
        let lastNameInfo = KASectionInfo(showHeader: true, sectionTitle: "Last name", sectionList: [lastName], type: .lastName)
        
        var_dataArray.append(idSectionInfo)
        var_dataArray.append(firstNameInfo)
        var_dataArray.append(middleNameInfo)
        var_dataArray.append(lastNameInfo)
    }
    func ka_setUI() {
        view.backgroundColor = .white
        view.addSubview(var_tableView)
        
        ka_showCustomerNavBar(type: .normal)
        var_navBar.var_titleLabel.text = "Obtain credit limit"
        
        let pusher = KASexPusher { gender, birthday in
            self.var_selectGender = gender
            self.var_selectBirthday = birthday
            self.var_model.overdueam = birthday
            self.var_model.startTimestamp = gender
            
            let btnInfo = KABtnInfo(eleId: "home_location_province", pageId: "individualIdentificationDetails", clickTime: Date.ka_currentData())
            KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
        }
        pusher.gender = var_model.startTimestamp
        pusher.birthday = var_model.overdueam
        pusher.ka_show()
    }
}

extension KAInfoVC : UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        var_dataArray.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let sectionData = var_dataArray[section]
        return sectionData.sectionList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let var_cell: KAApplyInfoCell = KAApplyInfoCell.ka_cell(for: tableView)
        let sectionData = var_dataArray[indexPath.section]
        let rowData = sectionData.sectionList[indexPath.row]
        var_cell.contentTF.placeholder = rowData.placeHolder
        var_cell.var_type = sectionData.type
        switch sectionData.type {
        case .identification:
            var_cell.contentTF.keyboardType = .numberPad
            var_cell.contentTF.text = var_model.bankVerificationNumberInput
            var_cell.editingHandle = { cell, content in
                if content.count > 11 {
                    cell.contentTF.text = String(content.prefix(11))
                }
                self.var_model.bankVerificationNumberInput = cell.contentTF.text!
            }
            var_cell.tfInfo = rowData.tfInfo
            var_cell.editDidEndHandle = { cell, tfInfo in
                tfInfo.geographicalLongitude = "property_ownership"
                tfInfo.paginationId = "individualIdentificationDetails"
                rowData.tfInfo = tfInfo
                KAReport.ka_reportWith(type: .tf, data: tfInfo.kj.JSONObject())
            }
        case .firstName:
            var_cell.contentTF.keyboardType = .default
            var_cell.contentTF.text = var_model.firstNameUser
            var_cell.editingHandle = { cell, content in
                let validCharacters = content.filter { char in
                    let charString = String(char)
                    return charString.verifyName
                }
                cell.contentTF.text = validCharacters
                self.var_model.firstNameUser = validCharacters
            }
            var_cell.tfInfo = rowData.tfInfo
            var_cell.editDidEndHandle = { cell, tfInfo in
                tfInfo.geographicalLongitude = "id_card_verification_number"
                tfInfo.paginationId = "individualIdentificationDetails"
                rowData.tfInfo = tfInfo
                KAReport.ka_reportWith(type: .tf, data: tfInfo.kj.JSONObject())
            }
        case .middleName:
            var_cell.contentTF.keyboardType = .default
            var_cell.contentTF.text = var_model.middleNameUser
            var_cell.editingHandle = { cell, content in
                let validCharacters = content.filter { char in
                    let charString = String(char)
                    return charString.verifyName
                }
                cell.contentTF.text = validCharacters
                self.var_model.middleNameUser = validCharacters
            }
            var_cell.tfInfo = rowData.tfInfo
            var_cell.editDidEndHandle = { cell, tfInfo in
                tfInfo.geographicalLongitude = "birth_date_information"
                tfInfo.paginationId = "individualIdentificationDetails"
                rowData.tfInfo = tfInfo
                KAReport.ka_reportWith(type: .tf, data: tfInfo.kj.JSONObject())
            }
        case .lastName:
            var_cell.contentTF.keyboardType = .default
            var_cell.contentTF.text = var_model.lastNameUser
            var_cell.editingHandle = { cell, content in
                let validCharacters = content.filter { char in
                    let charString = String(char)
                    return charString.verifyName
                }
                cell.contentTF.text = validCharacters
                self.var_model.lastNameUser = validCharacters
            }
            var_cell.tfInfo = rowData.tfInfo
            var_cell.editDidEndHandle = { cell, tfInfo in
                tfInfo.geographicalLongitude = "company_joining_date"
                tfInfo.paginationId = "individualIdentificationDetails"
                rowData.tfInfo = tfInfo
                KAReport.ka_reportWith(type: .tf, data: tfInfo.kj.JSONObject())
            }
        default: break
        }
        return var_cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return kscale(50.0)
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "KAApplyTitleHeader") as! KAApplyTitleHeader
        let sectionData = var_dataArray[section]
        header.titleLabel.text = sectionData.sectionTitle
        return header
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return kscale(30)
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        if section == 0 {
            let footer = tableView.dequeueReusableHeaderFooterView(withIdentifier: "KAApplySectionFooter") as! KAApplySectionFooter
            return footer
        }
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == 0 {
            return kscale(80)
        }
        return .leastNormalMagnitude
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    //    func scrollViewDidScroll(_ scrollView: UIScrollView) {
    //        view.endEditing(true)
    //    }
    //    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    //        view.endEditing(true)
    //    }
}
